package com.cnap.db.handler;

import cn.hutool.core.text.CharSequenceUtil;
import com.cnap.utils.JsonUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 将map转为字符串的handler
 *
 * @author xc
 **/
public class MapHandler implements TypeHandler<List<Map<String, String>>> {
    @Override
    public void setParameter(PreparedStatement preparedStatement, int i, List<Map<String, String>> strings, JdbcType jdbcType) throws SQLException {
        String str = JsonUtil.objectToJsonStr(strings);
        preparedStatement.setString(i, str);
    }

    @Override
    public List<Map<String, String>> getResult(ResultSet resultSet, String s) throws SQLException {
        if (CharSequenceUtil.isEmpty(resultSet.getString(s))) {
            return Collections.emptyList();
        }
        return JsonUtil.jsonStrToObject(resultSet.getString(s), new TypeReference<List<Map<String, String>>>() {
        });
    }

    @Override
    public List<Map<String, String>> getResult(ResultSet resultSet, int i) throws SQLException {
        if (CharSequenceUtil.isEmpty(resultSet.getString(i))) {
            return Collections.emptyList();
        }
        return JsonUtil.jsonStrToObject(resultSet.getString(i), new TypeReference<List<Map<String, String>>>() {
        });
    }

    @Override
    public List<Map<String, String>> getResult(CallableStatement callableStatement, int i) throws SQLException {
        if (CharSequenceUtil.isEmpty(callableStatement.getString(i))) {
            return Collections.emptyList();
        }
        return JsonUtil.jsonStrToObject(callableStatement.getString(i), new TypeReference<List<Map<String, String>>>() {
        });
    }

}
